/**   
* @Title: PayInfoController.java 
* @Package com.leesche.zcsp.node.web.controller.pay
* @Description:() 
* @author dennies yang
* @date 2016年9月29日 下午3:31:29 
* @version V1.0   
*/
package com.leesche.zcsp.node.web.controller.pay;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.leesche.zcsp.node.net.service.NetService;
import com.leesche.zcsp.node.pay.wecha.utils.SignUtil;
import com.leesche.zcsp.node.web.service.impl.data.read.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.leesche.zcsp.node.pay.alipay.service.AlipayService;
import com.leesche.zcsp.node.pay.wecha.data.Message;
import com.leesche.zcsp.node.pay.wecha.data.Oauth2To;
import com.leesche.zcsp.node.pay.wecha.data.XmlParam;
import com.leesche.zcsp.node.pay.wecha.service.PayService;
import com.leesche.zcsp.node.pay.wecha.service.WechatService;
import com.leesche.zcsp.node.pay.wecha.timer.WechatTimer;
import com.leesche.zcsp.node.pay.wecha.utils.Signature;
import com.leesche.zcsp.node.utils.PayConfig;
import com.leesche.zcsp.node.utils.TenpayUtil;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.model.PubDevice;
import com.leesche.zcsp.node.web.model.PubDiscount;
import com.leesche.zcsp.node.web.model.ServOrder;
import com.leesche.zcsp.node.web.service.PubDeviceService;
import com.leesche.zcsp.node.web.service.PubDevicecodeService;
import com.leesche.zcsp.node.web.service.PubDiscountService;
import com.leesche.zcsp.node.web.service.ServOrderService;
import com.leesche.zcsp.node.web.service.SysNoticeService;
import com.leesche.zcsp.node.web.service.impl.data.writ.UpdateServOrderCommad;

/**
 * @Title: PayInfoController.java
 * @Package com.leesche.zcsp.node.web.controller.pay
 * @Description:()
 * @author dennies yang
 * @date 2016年9月29日 下午3:31:29
 * @version V1.0
 */
@Controller("payinfo")
@RequestMapping(value = { "payinfo1", "/payinfo" })
public class PayInfoController {
	private static final Logger LOGGER = Logger.getLogger(PayInfoController.class);
	
	//界面	
	//支付宝预支付返回
	private static final String ALIPAYRETURN_VIEW="pay/alipayReturn";
	
	
	
	@Autowired
	PayService payService;

	@Autowired
	PubDiscountService pubDiscountService;

	@Autowired
	PubDevicecodeService pubDevicecodeService;

	@Autowired
	ServOrderService serviceOrderService;

	@Autowired
	PubDeviceService pubDeviceService;

	@Autowired
	SysNoticeService sysNoticeService;

	@Autowired
	WechatService wechatService;

	@Autowired
	AlipayService alipayService;

	@Autowired
	private NetService netService;
	
	/***
	 * 
	 * @Title: payView @Description: TODO(设备支付界面 微信和支付宝) @param @param
	 *         userAgent @param @param shortCode @param @param
	 *         request @param @param model @param @return @return String @throws
	 */
	@RequestMapping(value = "{shortCode}/pay", method = RequestMethod.GET)
	public String payView(@RequestHeader("User-Agent") String userAgent,
			final @PathVariable("shortCode") String shortCode, HttpServletRequest request, ModelMap model) {

		// 如果是微信浏览器
		if (payService.isWechatBrower(userAgent)) {
			StringBuffer url = new StringBuffer();
			url.append(request.getScheme());
			url.append("://");
			url.append(request.getServerName());
			url.append("/node/payinfo/");
			url.append("wechatPayView");
			url.append("/");
			url.append(shortCode);
			return "redirect:" + wechatService.getWechatRedirectUrl(url.toString());

		} else if (payService.isAlipayBrower(userAgent)) {
			/**** 支付宝浏览器 **/
			// 优惠信息
			QueryPubDiscountCondition condition = new QueryPubDiscountCondition();
			condition.setPaymenturlcode(shortCode);
			List<PubDiscountDto> list = pubDiscountService.findPubDiscountByShortCode(condition);
			model.put("discounts", list);
			// 读取设备ID

			QueryPubDeviceCondition deviceCondition =new QueryPubDeviceCondition();
			deviceCondition.setMac(shortCode);
			PubDeviceDto pubDeviceDto =pubDeviceService.findByCondition(deviceCondition);

			//Integer deviceId = pubDeviceService.getDeviceIDByShortCode(shortCode);
			model.put("status",netService.isOnline(pubDeviceDto.getImme()));
			model.put("deviceId", pubDeviceDto.getDeviceid());
			// 读取用户LOGO和公司名称
			SysNoticeDto sysNoticeDto = sysNoticeService.findSysNotice(pubDeviceDto.getDeviceid().intValue());
			// 如果sysNoticeDto为null 则使用默认的公司名称和LOGO
			if (sysNoticeDto == null) {
				sysNoticeDto = sysNoticeService.getDefaultSysNotice();
			}
			model.put("sysNotice", sysNoticeDto);
			return "pay/alipayDiscount";

		} else {
			// 其他浏览器
			return "pay/errorpay";
		}

	}	
	
	
	/**
	 * 
	* @Title: alipayRuturn 
	* @Description: TODO(支付支付成功后返回) 
	* @param @return   
	* @return String   
	* @throws
	 */
	@RequestMapping(value = "alipayRuturn", method = RequestMethod.GET)
	public String alipayRuturn( ) {
			return ALIPAYRETURN_VIEW;
	}
	
	
/*	@RequestMapping(value = "test", method = RequestMethod.GET)
	public String payView( HttpServletRequest request, ModelMap model) {
			// 如果是微信浏览器
			StringBuffer url = new StringBuffer();
			url.append(request.getScheme());
			url.append("://");
			url.append(request.getServerName());
			url.append("/"+Constants.SITE_NAME+"/payinfo/");
			url.append("wechatTransfers");
			return "redirect:" + wechatService.getWechatRedirectUrl(url.toString());
	}
	
	*/
	/***
	 * 
	* @Title: giveMoney 
	* @Description: TODO(微信提取现金) 
	* @param @param request
	* @param @param response   
	* @return void   
	* @throws
	 *//*
	public Message<String> wechattransfers(String code,int money,HttpServletRequest request, HttpServletResponse response) {
\	
	@RequestMapping(value = "wechatTransfers", method = RequestMethod.GET)
	public Message<String> String wechattransfers(String code,int money,HttpServletRequest request, HttpServletResponse response) {
		Message<Oauth2To> oauth2ToM=wechatService.getOauth(code);
		if(oauth2ToM!=null&&oauth2ToM.isError(oauth2ToM.getType())){
			//return Message.error("获取用户信息失败", null);
		}
		String ip = "";
		if (request.getHeader("x-forwarded-for") == null) {
			ip = request.getRemoteAddr();
		} else {
			ip = request.getHeader("x-forwarded-for");
		}	
		String orderNo=SignUtil.getOrderNo();

		return wechatService.wechattransfers(ip, oauth2ToM.getContent().getOpenid(), money, "临时说明", TenpayUtil.getCharacterEncoding(request, response),orderNo);
		
		return "pay/wechatpay";
	}
*/


	/***
	 * 
	 * @Title: wechatPayView @Description: TODO(微信支付界面) @param @return @return
	 *         String @throws
	 */
	@RequestMapping(value = "wechatPayView/{shortCode}", method = RequestMethod.GET)
	public String wechatPayView(@RequestHeader("User-Agent") String userAgent,
			final @PathVariable("shortCode") String shortCode, String code, HttpServletRequest request,
			ModelMap model) {
		Message<Oauth2To> message = wechatService.getOauth(code);
		if (message.getType() == Message.Type.error) {
			// 读取用户信息失败
		} else if (message.getType() == Message.Type.success) {
			// 优惠信息
			QueryPubDiscountCondition condition = new QueryPubDiscountCondition();
			condition.setPaymenturlcode(shortCode);
			List<PubDiscountDto> list = pubDiscountService.findPubDiscountByShortCode(condition);
			model.put("discounts", list);
			// 读取设备ID
	/*		Integer deviceId = pubDeviceService.getDeviceIDByShortCode(shortCode);
			model.put("deviceId", deviceId);*/
			QueryPubDeviceCondition deviceCondition =new QueryPubDeviceCondition();
			deviceCondition.setMac(shortCode);
			PubDeviceDto pubDeviceDto =pubDeviceService.findByCondition(deviceCondition);

			//Integer deviceId = pubDeviceService.getDeviceIDByShortCode(shortCode);
			model.put("status",netService.isOnline(pubDeviceDto.getImme()));
			model.put("deviceId", pubDeviceDto.getDeviceid());
			// 读取用户LOGO和公司名称
			SysNoticeDto sysNoticeDto = sysNoticeService.findSysNotice(pubDeviceDto.getDeviceid().intValue());
			// 如果sysNoticeDto为null 则使用默认的公司名称和LOGO
			if (sysNoticeDto == null) {
				sysNoticeDto = sysNoticeService.getDefaultSysNotice();
			}
			model.put("sysNotice", sysNoticeDto);

			model.put("openid", message.getContent().getOpenid());
			String url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI() + "?"
					+ request.getQueryString();

			model.put("jsret", SignUtil.sign(WechatTimer.JS_TIKET, url));

			return "pay/wechatpay";

		}
		return null;

	}

	/**
	 * 
	* @Title: prePayInAlipay 
	* @Description: TODO(支付宝预支付回调) 
	* @param @param deviceid
	* @param @param discountid
	* @param @param openid
	* @param @param request
	* @param @return   
	* @return Map<String,Object>   
	* @throws
	 */
	@ResponseBody
	@RequestMapping(value = "prePayInAlipay", method = RequestMethod.POST)
	public Map<String, Object> prePayInAlipay(Long deviceid, Long discountid, String openid,
			HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();

		PubDiscount pubDiscount = pubDiscountService.selectByPrimaryKey(discountid);
		PubDevice pubDevice = pubDeviceService.selectByPrimaryKey(deviceid);
		if (pubDiscount != null&&pubDevice!=null) {
			String orderNo = TenpayUtil.getOrderNo();
			ServOrder order = new ServOrder();
			order.setCreatetime(new Date());
			order.setCashFee(pubDiscount.getMoney()*100);//存储以分为单位
			order.setCoin(pubDiscount.getCoin());
			order.setDeviceid(deviceid);
			order.setDiscountid(discountid);
			order.setTimeEnd(new Date());
			order.setTransactionId("");
			order.setTradeStateDesc("下订单");
			order.setTradeState(Constants.WECHAT_NOTPAY);
			order.setOutTradeNo(orderNo);
			order.setOpenid(openid);
			order.setUserid(pubDevice.getAdminid());
			LOGGER.info("支付宝下订单时 :"+orderNo);
			if (serviceOrderService.insert(order) > 0) {
				map.put("orderinfo", alipayService.orderAlipay(order));
				map.put("message", Message.success("下单成功", new Object[0]));
				return map;
			}
		}
		map.put("message", Message.error("下单失败!", new Object[0]));

		return map;
	}

	/***
	 * 
	 * @Title: notifyAlipay @Description: TODO(支付宝支付回调) @param @param
	 * request @param @param response @param @throws
	 * UnsupportedEncodingException @return void @throws
	 */
	@ResponseBody
	@RequestMapping(value = "notifyAlipay", method = RequestMethod.POST)
	public String notifyAlipay(String out_trade_no, String trade_no, String trade_status, HttpServletRequest request,
			HttpServletResponse response) {
		return alipayService.notifyAlipay(request.getParameterMap(), out_trade_no, trade_no, trade_status).getContent();
		// return content;

	}

	/***
	 * 
	 * @Title: prePay @Description: TODO(微信预支付预支付下订单) @param @param
	 *         deviceid @param @param discountid @param @param
	 *         openid @param @param request @param @return @return
	 *         Map<String,Object> @throws
	 */
	@ResponseBody
	@RequestMapping(value = "prepay", method = RequestMethod.POST)
	public Map<String, Object> prePayInWechat(Long deviceid, Long discountid, String openid,
			HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		PubDiscount pubDiscount = pubDiscountService.selectByPrimaryKey(discountid);
		PubDevice pubDevice = pubDeviceService.selectByPrimaryKey(deviceid);
		if (pubDiscount != null&&pubDevice!=null) {
			String orderNo = TenpayUtil.getOrderNo();
			ServOrder order = new ServOrder();
			order.setCreatetime(new Date());
			order.setCashFee(pubDiscount.getMoney()*100); //存储以分为单位
			order.setCoin(pubDiscount.getCoin());
			order.setDeviceid(deviceid);
			order.setDiscountid(deviceid);
			order.setTimeEnd(new Date());
			order.setTransactionId("");
			order.setTradeStateDesc("下订单");
			order.setTradeState(Constants.WECHAT_NOTPAY);
			order.setOutTradeNo(orderNo);
			order.setOpenid(openid);
			order.setUserid(pubDevice.getAdminid());
			if (serviceOrderService.insert(order) > 0) {
				String ip = "";
				if (request.getHeader("x-forwarded-for") == null) {
					ip = request.getRemoteAddr();
				} else {
					ip = request.getHeader("x-forwarded-for");
				}
				Message<String> message = wechatService.prePay(order, ip, openid, "JSAPI");
				if (message.getType() == Message.Type.success) {
					map.put("appId", PayConfig.appid);
					map.put("timeStamp", SignUtil.create_timestamp());
					map.put("nonceStr", SignUtil.getRandomStringByLength(32));
					map.put("package", "prepay_id=" + message.getContent());
					map.put("signType", "MD5");
					map.put("paySign", Signature.getSign(map));
				}
				map.put("message", message);
			}

		}

		return map;
	}

	/**
	 * 
	 * @Title: NotifyUrl @Description: TODO(微信支付回调信息) @param @param
	 * request @param @return @param @throws IOException @return String @throws
	 */
	@RequestMapping(value = { "notify" }, method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String NotifyUrl(HttpServletRequest request) throws IOException {
		String resXml = "";

		XmlParam param = new XmlParam(request.getInputStream());
		System.out.println("支付订单号" + param.getParam("out_trade_no"));
		System.out.println("交易号" + param.getParam("transaction_id"));
		if (param.getParam("result_code").equals("SUCCESS")) {
			serviceOrderService.updateServOrderByOrderNo(new UpdateServOrderCommad(Constants.WECHAT_SUCCESS,
					param.getParam("transaction_id"), param.getParam("out_trade_no")));
			resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml> ";
		} else {
			resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml> ";
		}

		return resXml;

	}

	/**
	 * @throws IOException *
	 * 
	 * @Title: onScanPay @Description: TODO(微信扫码支付) @param @param
	 * request @param @param response @param @throws IOException @return
	 * void @throws
	 */

	@RequestMapping(value = "onScanPay", method = RequestMethod.POST)
	@ResponseBody
	public String onScanPay(HttpServletRequest request, HttpServletResponse response) throws IOException {
		XmlParam param = new XmlParam(request.getInputStream());
		Message<String> message = null;
		String productid = param.getParam("product_id"); // productid =
															// deviceid// +"-"+
															// discountid;
		String data[] = productid.split(Constants.SPILTTMARK);
		String deviceid = data[0];
		String discountid = data[1];
		PubDiscount pubDiscount = pubDiscountService.selectByPrimaryKey(Long.valueOf(discountid));
		PubDevice pubDevice = pubDeviceService.selectByPrimaryKey(Long.valueOf(deviceid));
		String orderNo = TenpayUtil.getOrderNo();
		ServOrder order = new ServOrder();
		order.setCreatetime(new Date());
		order.setCashFee(pubDiscount.getMoney()*100);//存储以分为单位
		order.setCoin(pubDiscount.getCoin());
		order.setDeviceid(Long.valueOf(deviceid));
		order.setDiscountid(Long.valueOf(discountid));
		order.setTimeEnd(new Date());
		order.setTransactionId("");
		order.setTradeStateDesc("下订单");
		order.setTradeState(Constants.WECHAT_NOTPAY);
		order.setOutTradeNo(orderNo);
		order.setOpenid(param.getParam("openid"));
		order.setUserid(pubDevice.getAdminid());
		if (serviceOrderService.insert(order) > 0) {
			String ip = "";
			if (request.getHeader("x-forwarded-for") == null) {
				ip = request.getRemoteAddr();
			} else {
				ip = request.getHeader("x-forwarded-for");
			}
			message = wechatService.prePay(order, ip, param.getParam("openid"), "NATIVE");
		}

		XmlParam res = wechatService.onScan(param.getParam("nonce_str"), message,
				TenpayUtil.getCharacterEncoding(request, response));

		return res.toString();

	}

	/***
	 * 
	 * @Title: preSinglePayInAlipay @Description: TODO(支付宝单局支付) @param @param
	 * deviceid 设备ID @param @param discountid 套餐ID @param @param
	 * openid @param @return @return Map<String,Object> @throws
	 */
	@RequestMapping(value = "{deviceid}/{discountid}/preSinglePayInAlipay", method = RequestMethod.GET)
	public String preSinglePayInAlipay(@RequestHeader("User-Agent") String userAgent,
			final @PathVariable("deviceid") Long deviceid, final @PathVariable("discountid") Long discountid,
			ModelMap model, HttpServletRequest request) {
		if (payService.isAlipayBrower(userAgent)) {
			PubDiscount pubDiscount = pubDiscountService.selectByPrimaryKey(discountid);
			PubDevice pubDevice = pubDeviceService.selectByPrimaryKey(Long.valueOf(deviceid));
			if (pubDiscount != null) {
				String orderNo = TenpayUtil.getOrderNo();
				ServOrder order = new ServOrder();
				order.setCreatetime(new Date());
				order.setCashFee(pubDiscount.getMoney()*100);
				order.setCoin(pubDiscount.getCoin());
				order.setDeviceid(deviceid);
				order.setDiscountid(deviceid);
				order.setTimeEnd(new Date());
				order.setTransactionId("");
				order.setTradeStateDesc("支付宝下订单");
				order.setTradeState(Constants.WECHAT_NOTPAY);
				order.setOutTradeNo(orderNo);
				order.setUserid(pubDevice.getAdminid());
				if (serviceOrderService.insert(order) > 0) {
					model.put("orderinfo", alipayService.orderAlipay(order));
					model.put("status",netService.isOnline(pubDevice.getImme()));
					return "pay/alipaySingle";
				}
			}
		} else {
			return "pay/errorpay";
		}

		// 其他情况未知错误
		return "pay/errorpay";

	}

}
